<template>
  <view
    class="radio-group"
    :class="[{ 'radio-group--collapse': collapse, 'radio-group--is-show': isShow, 'radio-group--inline': inline }]"
  >
    <view v-if="title" class="radio-group__header">
      <view class="title">
        {{ $t(title) }}
        <view v-if="eye" class="eye" @click="handleEye">
          <m-icon :name="isShow ? 'eye' : 'eye-hidden'" size="32" color="inherit" />
        </view>
      </view>
      <m-icon :name="right" size="32" color="inherit" @click="handleClick(right)" />
    </view>
    <view class="radio-group__content">
      <slot />
      <view v-if="collapse && line > lineMin && overflow" class="radio-group__collapse" @click="handleToggle">
        <m-icon :name="isOpen ? 'arrow-up' : 'arrow-down'" size="16" color="inherit" />
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent, provide, watch, ref, inject, onMounted } from '@vue/composition-api'
import boundingClientRect from '@/utils/bounding-client-rect'
import getCurrentComponent from '@/utils/get-current-component'

export default defineComponent({
  props: {
    value: {
      type: [String, Number],
      default: null,
    },
    textPosition: {
      type: String,
      default: 'right',
    },
    size: {
      type: String,
      default: 'md',
    },
    title: {
      type: String,
      default: '',
    },
    collapse: {
      type: Boolean,
      default: false,
    },
    right: {
      type: String,
      default: '',
    },
    eye: {
      type: Boolean,
      default: false,
    },
    inline: {
      type: Boolean,
      default: false,
    },
    contentDisabled: {
      type: Boolean,
      default: false,
    },
    emptyValue: {
      type: Boolean,
      default: true,
    },
    lineMin: {
      type: Number,
      default: 2,
    },
    overflow: {
      type: Boolean,
      default: true,
    },
  },
  emits: ['change', 'del', 'refresh', 'update:collapse', 'eye', 'toggle'],
  setup(props, { emit }) {
    const vm = getCurrentComponent()
    const formItem: any = inject('formItem', null)
    const radioList: any[] = []
    let radioGroupMap = {}
    const isOpen = ref(false)
    const lineMap = {}
    const hideList: any = []
    const handleToggle = () => {
      isOpen.value = !isOpen.value

      hideList.forEach((radio) => {
        radio.vm.setHide(!isOpen.value)
      })

      emit('collapse', isOpen.value)
      emit('toggle', isOpen.value)
    }
    const handleClick = (type) => {
      emit(type)
    }
    const line = ref(0)
    const isShow = ref(true)
    const handleEye = () => {
      isShow.value = !isShow.value
      emit('eye', isOpen.value)
    }

    let line2LastTimer
    const setLine2Last = () => {
      const line2Top = lineMap['1']
      const line2items = radioGroupMap[line2Top]
      if (!(line2items && line2items.length)) {
        return
      }
      const line2lastItem = line2items[line2items.length - 1]
      const parentWidth = parentRect.left + parentRect.width

      if (line2lastItem.boxInfo.right + 38 > parentWidth) {
        line2lastItem.vm.setHide(true)
        hideList.push(line2lastItem)
      }
      // uni.$emit('historyChange', 88)
    }
    let parentRect

    provide('radioParent', {
      radioList,
      textPosition: props.textPosition,
      size: props.size,
      collapse: props.collapse,
      inline: props.inline,
      contentDisabled: props.contentDisabled,
      addRadio(radio) {
        radioList.push(radio)
        if (radio.boxInfo) {
          if (!radioGroupMap[radio.boxInfo.top]) {
            lineMap[Object.keys(lineMap).length] = radio.boxInfo.top
            radioGroupMap[radio.boxInfo.top] = []
          }

          radioGroupMap[radio.boxInfo.top].push(radio)

          line.value = Object.keys(radioGroupMap).length

          if (Object.keys(radioGroupMap).length > props.lineMin) {
            hideList.push(radio)
            radio.vm.setHide(true)
          }

          if (line2LastTimer) {
            clearTimeout(line2LastTimer)
          }

          // 延迟只执行1次
          line2LastTimer = setTimeout(setLine2Last, 20)
        }
        // init
        radio.vm.setCheck(radio.label, props.value)
      },
      removeRadio(label) {
        const index = radioList.findIndex((x) => x.label === label)

        radioList.splice(index, 1)
      },
      radioClick(label) {
        if (props.value === label && props.emptyValue) {
          return
        } else {
          emit('input', label)
        }
      },
    })

    watch(
      () => props.value,
      (newVal) => {
        radioList.forEach((radio) => {
          radio.vm.setCheck(radio.label, newVal)
        })
        emit('change', newVal)
        if (formItem && formItem.validate) {
          formItem && formItem.validate()
        }
      }
    )

    onMounted(async () => {
      if (props.collapse) {
        parentRect = await boundingClientRect('.radio-group', vm)
      }
    })

    return {
      isOpen,
      line,
      handleToggle,
      handleClick,
      isShow,
      handleEye,
    }
  },
})
</script>
<style lang="scss" scoped>
.radio-group {
  width: 100%;
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;
  }
  &__collapse {
    background: $--bg-body-c;
    width: 56rpx;
    height: 56rpx;
    background: $--bg-body-c;
    border-radius: 6rpx;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: $--font-primary-c;
  }
  .title {
    font-weight: bold;
    color: $--font-primary-c;
    font-size: 28rpx;
    display: flex;
  }
  .eye {
    margin-left: 10rpx;
  }
  .radio-group__content {
    display: none;
    // max-height: 300rpx;
    // overflow: auto;
  }
  &--is-show {
    .radio-group__content {
      display: block;
    }
    &.radio-group--inline {
      .radio-group__content {
        display: flex;
      }
    }
  }
}
</style>
